<?php

namespace app\admin\command;

use app\admin\model\Client;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Exception;
use think\Log;

class WashClientGender extends Command
{
    protected $clientModel;
    public function __construct($name = null)
    {
        $this->clientModel = new Client();

        parent::__construct($name);
    }
    protected function configure()
    {
        $this->setName('WashClientGender')
            ->setDescription('根据用户身份证修正用户性别、年龄');
    }

    protected function execute(Input $input, Output $output)
    {
        $output->info("WashClientGender start ".date('Y-m-d H:i:s'));
        try {
            $list = $this->clientModel->field('id,id_number')->select();
            if($list){
                foreach ($list as $item){
                    $this->updateGender($item->id, $item->id_number, $output);
                }
            }
        }catch (\Exception $e){
            $output->writeln('Update 数据出错：'.$e->getMessage());
        }
        $output->info("WashClientGender Successed ".date('Y-m-d H:i:s'));
    }

    function updateGender($id, $idcard, $output){
        try {
            $gender = $this->getGenderByIdCard($idcard);
            $privateArr = $this->getAgeBirthByIdCard($idcard);
            Log::log(json_encode(['gender' => $gender, 'age' => $privateArr['age'], 'birth_date' => $privateArr['birthdate']],));
            $this->clientModel->update(
                ['gender' => $gender, 'age' => $privateArr['age'], 'birth_date' => $privateArr['birthdate']],
                ['id' => $id]
            );
        }catch (Exception $exception){
            Log::error($exception->getMessage());
        }

        Log::log($this->clientModel->getLastSql());
        $output->info($this->clientModel->getLastSql());
    }

    /**
     * 判断性别
     * @param $idCard
     * @return int|string
     */
    function getGenderByIdCard($idCard) {
        // 验证身份证号码长度是否为18位
        if (strlen($idCard) !== 18) {
            return "无效的身份证号码（长度不正确）";
        }

        // 获取第17位字符（索引16）
        $genderDigit = $idCard[16];

        // 判断性别：奇数男，偶数女
        return ((int)$genderDigit % 2 === 1) ? 1 : 2;
    }


    function getAgeBirthByIdCard($idCard) {
        // 设置时区（根据实际需求调整）
        date_default_timezone_set('Asia/Shanghai');

        // 验证身份证长度
        $length = strlen($idCard);
        if (!in_array($length, [15, 18])) {
            return "身份证号码长度无效";
        }

        // 提取出生日期部分
        if ($length === 18) {
            $dateStr = substr($idCard, 6, 8);  // 提取YYYYMMDD
        } else {
            $dateStr = '19' . substr($idCard, 6, 6); // 15位身份证补全为19YYMMDD
        }

        // 将日期字符串转换为DateTime对象
        $birthDate = \DateTime::createFromFormat('Ymd', $dateStr);
        if (!$birthDate) {
            return "身份证包含无效的出生日期";
        }

        // 获取当前日期对象
        $today = new \DateTime();

        // 计算年龄差异
        $age = $today->diff($birthDate)->y;

        // 精确校验是否已过生日（精确到天）
        $currentMonthDay = $today->format('md');
        $birthMonthDay = $birthDate->format('md');

        // 如果今天还没到生日月日，年龄减1
        $age = intval(($currentMonthDay < $birthMonthDay) ? $age - 1 : $age);
        return [
            'birthdate' => $this->convertDateFormat($dateStr),
            'age' => $age
        ];
    }

    function convertDateFormat($dateStr) {
        // 分割年月日
        $year  = substr($dateStr, 0, 4);
        $month = substr($dateStr, 4, 2);
        $day   = substr($dateStr, 6, 2);

        // 格式化为YYYY-MM-DD
        return sprintf("%04d-%02d-%02d", $year, $month, $day);
    }






}